package com.shqcjd.preinstallglass.ui.base;

import android.app.Dialog;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;


import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.util.AppManager;
import com.shqcjd.preinstallglass.util.StatusBarCompat;
import com.shqcjd.preinstallglass.widget.CustomDialog;

import butterknife.ButterKnife;
import cn.ceyes.services.voice.GlassVoiceConst;
import cn.ceyes.services.voice.GlassVoiceResult;
import cn.ceyes.services.voice.GlassVoiceService;
import cn.ceyes.services.voice.GlassVoiceServiceObserver;


public abstract class BaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity{

    private GlassVoiceService mVoiceService = GlassVoiceService.getInstance();
    protected T mPresenter;
    private CustomDialog mDialogWaiting;
    private int mMode;
    private Context mContext;
    private SoundPool soundPool;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        MyApp.activities.add(this);
        if (isFullScreen()) {
            //去除title
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            //去掉Activity上面的状态栏
            getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN , WindowManager.LayoutParams. FLAG_FULLSCREEN);
        }

        init();

        //判断是否使用MVP模式
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.attachView((V) this);//因为之后所有的子类都要实现对应的View接口
        }

        //子类不再需要设置布局ID，也不再需要使用ButterKnife.bind()
        setContentView(provideContentViewId());
        ButterKnife.bind(this);

        excuteStatesBar();
        initView();
        initData();
        initListener();

        //初始化SoundPool
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM,5);
        //加载deep 音频文件
        soundPool.load(mContext,R.raw.sound_success,1);

        AppManager.getAppManager().addActivity(this);


    }

    /**
     * 解决4.4设置状态栏颜色之后，布局内容嵌入状态栏位置问题
     */
    private void excuteStatesBar(){
        ViewGroup mContentView = (ViewGroup) getWindow().findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows,
            // 而是设置 ContentView 的第一个子 View ，预留出系统 View 的空间.
            mChildView.setFitsSystemWindows(true);
        }
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor() {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorAccent));
    }


    /**
     * 沉浸状态栏（4.4以上系统有效）
     */
    protected void SetTranslanteBar() {
        StatusBarCompat.translucentStatusBar(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }

        if (isStopVoiceService()) {
            // stop service
            mVoiceService.stopService();
        }

    }

    /**
     * 是否全屏
     * @return
     */
    protected boolean isFullScreen() {
        return true;
    }

    /**
     * 是否关闭语音识别
     * @return
     */
    protected boolean isStopVoiceService(){
        return false;
    }

    //在setContentView()调用之前调用，可以设置WindowFeature(如：this.requestWindowFeature(Window.FEATURE_NO_TITLE);)
    public void init() {
    }

    public void initView() {
    }

    public void initData() {
    }

    public void initListener() {
    }

    //用于创建Presenter和判断是否使用MVP模式(由子类实现)
    protected abstract T createPresenter();

    //得到当前界面的布局文件id(由子类实现)
    protected abstract int provideContentViewId();


    protected  void onVoiceResult(String result){

    }

    protected String getVoiceContent(){
        return "|返回;";
    }

    /**
     * 是否默认在onResume里面初始化语音
     * @return
     */
    protected boolean isAutomaticInitVoice(){
        return true;
    }

    /**
     * 输入语音指令
     * @return
     */
    protected void getVoiceContent(String str){
        mVoiceService.startListening(GlassVoiceService.LocalDynamicRecognizer, str);
    }

    /**
     * 显示等待提示框
     */
    public Dialog showWaitingDialog(String tip) {
        hideWaitingDialog();
        View view = View.inflate(this, R.layout.dialog_waiting, null);
        if (!TextUtils.isEmpty(tip))
            ((TextView) view.findViewById(R.id.tvTip)).setText(tip);
        mDialogWaiting = new CustomDialog(this, view, R.style.MyDialog);
        mDialogWaiting.show();
        mDialogWaiting.setCancelable(false);
        return mDialogWaiting;
    }

    /**
     * 隐藏等待提示框
     */
    public void hideWaitingDialog() {
        if (mDialogWaiting != null) {
            mDialogWaiting.dismiss();
            mDialogWaiting = null;
        }
    }

    /**
     * 是否使用语音输入
     * @return
     */
    public boolean isVoiceType(){
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVoiceService.registerObserver(this.mGlassVoiceServiceObserver);

        // (1) 本地静态模式
//        mVoiceService.startListening(GlassVoiceService.LocalStaticRecognizer, null);

        // (2) 局部动态模式
//        mVoiceService.startListening(GlassVoiceService.LocalDynamicRecognizer, "|张三|李四|王五;");

        if(isVoiceType()){
            mVoiceService.startListening(GlassVoiceService.CloudRecognizer, null);
            mMode = GlassVoiceService.CloudRecognizer;
        }else{
            if(isAutomaticInitVoice()){
                Logger.i("识别内容:"+getVoiceContent());
                mVoiceService.startListening(GlassVoiceService.LocalDynamicRecognizer, getVoiceContent());
            }
        }
        // (3) 云模式
//        mVoiceService.startListening(GlassVoiceService.CloudRecognizer, null);
//        mMode = GlassVoiceService.CloudRecognizer;
    }

    private GlassVoiceServiceObserver mGlassVoiceServiceObserver = new GlassVoiceServiceObserver() {
        public boolean onResult(GlassVoiceResult result, boolean isLast) {
            String word = result.getFinalString();

            //播放声音
            soundPool.play(1, 1, 1, 0, 0, 1);

            Logger.i("识别结果:"+word);
            onVoiceResult(word);
            // if you want to keep recognizing voice in cloud mode,
            // you should listen again after last word.
            if (mMode == GlassVoiceService.CloudRecognizer && isLast) {
                mVoiceService.startListening(GlassVoiceService.CloudRecognizer, null);
            }

            return true;
        }

        public void onError(int errorCode) {
            // ignore ERROR_NO_MATCH for it is happened so frequently
            if (errorCode == GlassVoiceConst.ERROR_NO_MATCH) { // ERROR_NO_MATCH
            } else {
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();

        // stop voice listening
        mVoiceService.unregisterObserver(this.mGlassVoiceServiceObserver);
        mVoiceService.stopListening();
    }


}
